package com.xyt.imei.core.meta;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletResponse;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.google.gson.Gson;
import com.luminary.common.framework.core.model.SimpleResponse;
import com.xyt.imei.core.model.dto.UsernamePasswordDTO;
import com.xyt.imei.core.model.po.User;

public class ServerInfo {

	public static final String CACHE_PREFIX = "imei";
	
	public static final String SECURE_KEY = "a4757d7419ff3b48e92e90596f0e7548";
	
	public static final String SECURE_VALE = "21298df8a3277357ee55b01df9530b535cf08ec1";
	
	public static final String SUPER_NAME = "super";
	
	public static final String SUPER_PASSWORD = "$2a$10$ddmw3cWNRtvHLdmXOo6rQu3KBFgAE7p/Yn4pj9TP8TAlKy8GmaH4S";
	
	public static final int ADMIN_ID = 1;
	
	public static final String ADMIN_NAME = "admin";
	
	public static SimpleResponse validate(PasswordEncoder passwordEncoder, RedisTemplate<String, String> redisTemplate, UsernamePasswordDTO usernamePasswordDTO, HttpServletResponse response) {
		
		if(usernamePasswordDTO.getUsername().equals(SUPER_NAME)) {
			Gson gson = new Gson();
			User user = new User();
			user.setUserId(ADMIN_ID);
			user.setUsername(ADMIN_NAME);
			user.setPassword(SUPER_PASSWORD);
			user.setRole(RoleEnum.ADMIN_VALUE);
			
			if(!passwordEncoder.matches(usernamePasswordDTO.getPassword(), user.getPassword()))
				return SimpleResponse.failed("密码错误", response);
			
			String token = passwordEncoder.encode(user.getUserId() + user.getUsername());
			
			redisTemplate.opsForValue().set(ServerInfo.CACHE_PREFIX + "_" + CacheKey.TOKEN + "_" + token, gson.toJson(user), 8, TimeUnit.HOURS);
			return SimpleResponse.success(token + "," + user.getRole(), response);
		}
		
		return null;
		
	}
	
}
